<!--
 * @Author: gy
 * @Date: 2019-12-24 15:13:01
 * @LastEditors  : wl
 * @LastEditTime : 2020-06-17 17:39:10
 -->
<!-- menuList -->
<template>
  <div class="layout-content">
    <el-form ref="form" :model="form" :rules="rules" label-width="110px">
      <el-form-item label="上级菜单" prop="parent_id">
        <el-input v-model="form['parent_name']" @focus="dialogVisibleMenu = true" placeholder="请选择部门名称" />
        <!-- <div class="select-depart" @click="dialogVisibleDepart = true">{{ treeObj.label ? treeObj.label: '选择部门' }}</div> -->
        <div v-if="dialogVisibleMenu">
          <el-dialog
            title="部门选择"
            :visible.sync="dialogVisibleMenu"
            width="30%"
            :destroy-on-close="true"
            :append-to-body= "true"
            top="30vh"
            :modal-append-to-body= "false"
            @close="dialogVisibleMenu = false">
            <div class="search-content">
              <div class="search-box">
                <el-input
                  placeholder="输入关键字进行过滤"
                  v-model="filterText">
                </el-input>
                <span class="search-btn" @click="searchTreeData">查询</span>
              </div>
              <div class="tree-box">
                <div class="tree-fold">
                  <span @click="foldTree">折叠</span>
                  <i> / </i>
                  <span @click="openTree">打开</span>
                </div>
                <el-tree
                  class="filter-tree"
                  :data="menuList"
                  :props="defaultProps"
                  :default-expand-all="expanded"
                  :check-strictly="true"
                  show-checkbox
                  node-key="id"
                  @check="treeCheck"
                  node-click="nodeClick"
                  @check-change="handleMetaNodeClick"
                  :filter-node-method="filterNode"
                  ref="tree">
                </el-tree>
              </div>
            </div>
            <!-- <el-cascader
              v-model="form['parent_id']"
              :options="menuList"
              :props="props"
              collapse-tags
              ref="menu"
              placeholder="请选择部门"
              :show-all-levels="false"
              clearable></el-cascader> -->
            <span slot="footer" class="dialog-footer">
              <el-button @click="selectDepartCancel">取 消</el-button>
              <el-button type="primary" @click="selectDepartConfirm">确 定</el-button>
            </span>
          </el-dialog>
        </div>
      </el-form-item>
      <el-form-item label="菜单类型" prop="menu_type">
        <el-radio-group v-model="form['menu_type']">
          <el-radio label="D">模块</el-radio>
          <el-radio label="M">目录</el-radio>
          <el-radio label="C">菜单</el-radio>
          <el-radio label="F">按钮</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="菜单名称" prop="menu_name">
        <el-input v-model="form['menu_name']" placeholder="请输入菜单名称" @blur="menuNameCheck" />
        <span class="errorText" v-show="form['checkParam']['uniqueMenuName']">该菜单名称重复</span>
      </el-form-item>
      <el-form-item label="请求地址" prop="url">
        <el-input v-model="form['url']" placeholder="请输入请求地址" />
      </el-form-item>
      <el-form-item label="权限标识">
        <el-input v-model="form['perms']" placeholder="请输入权限标识" />
      </el-form-item>
      <el-form-item label="显示顺序" prop="order_num">
        <el-input type="number" v-model.number="form['order_num']" placeholder="请输入显示顺序" />
      </el-form-item>
      <el-form-item label="图标">
        <el-input v-model="form['icon']" placeholder="请选择图标" />
      </el-form-item>
      <el-form-item label="菜单状态" prop="visible">
        <el-radio-group v-model="form['visible']">
          <el-radio label="0">显示</el-radio>
          <el-radio label="1">隐藏</el-radio>
        </el-radio-group>
      </el-form-item>
    </el-form>
    <!-- <div class="handle-btn">
      <el-button type="primary" @click="handleConfirm">确定</el-button>
      <el-button @click="handleCancel">关闭</el-button>
    </div> -->
  </div>
</template>

<script>
import {
  getMenuForParent,
  getMenuTreeData,
  getRoleMenuTreeData,
  checkMenuNameUnique // 菜单名唯一性
} from "@/api/api";
import SystemMixin from "@/mixins/SystemMixin";
export default {
  name: "AddMenu",
  props: {
    titles: {
      type: String,
      default: () => ""
    }
  },
  mixins: [SystemMixin],
  data() {
    // let parentId = (rule, value, fn) => {
    //   let idList = this.$refs["menu"].getCheckedNodes();
    //   if (idList.length === 0) {
    //     fn(new Error("请选择上级菜单"));
    //   } else {
    //     fn();
    //   }
    // };
    return {
      dialogVisibleMenu:false,
      editCheckId: "", // 单选
      filterText: "",
      treeData: [], // tree树
      defaultProps: {
        children: "children",
        label: "name"
      },
      expanded: false, // 折叠打开
      form: {
        parent_id: "",
        parent_name: "",
        menu_name: "",
        menu_type: "", // 菜单类型
        url: "",
        perms: "",
        order_num: null,
        visible: "0", // 菜单状态
        // 唯一性检测
        checkParam: {
          uniqueMenuName: false
        },
      },

      // 查询菜单信息(包含父元素)
      menuParentInfo: {},
      menuList: [],
      moduleHidden: false,
      menuForParentName: "",
      props: { multiple: true },
      rules: {
        // parent_id: [
        //   {
        //     validator: parentId,
        //     required: true,
        //     trigger: "blur"
        //   }
        // ],
        menu_name: [
          {
            required: true,
            message: "请输入菜单名称",
            trigger: "blur"
          }
        ],
        menu_type: [
          {
            required: true,
            message: "请输入权限字符",
            trigger: "change"
          }
        ],
        url: [
          {
            required: true,
            message: "请输入请求地址",
            trigger: "change"
          }
        ],
        order_num: [
          {
            required: true,
            message: "请输入显示顺序",
            trigger: "blur"
          }
        ],
        visible: [
          {
            required: true,
            message: "请选择状态",
            trigger: "change"
          }
        ]
      }
    };
  },
  mounted() {
    // // 上级菜单-子集菜单新增
    // getMenuForParent({ pid: ''}).then(res => {
    //   if(res.code === 0) {
    //     // 查询菜单信息
    //     this.menuParentInfo = res['data'] ? res['data'] : {}
    //     // this.menuForParentName = res['data']['parent_name'] ? res['data']['parent_name'] : '系统管理'
    //   }
    // })
    // 菜单树(全部)
    getMenuTreeData().then(res => {
      if (res.code === 0) {
        // console.log(this.menuList, 'this.menuList')
        this.menuList = this.assembleTreeData(res.data, 'id', 'pId');
        console.log(this.menuList, 'this.menuList')
      }
    });
    // // 由角色获取对应菜单
    // getRoleMenuTreeData({roleId:this.uid}).then(res => {
    //   if(res.code === 0) {
    //     // this.menuList = res.data
    //     console.log(res, 'getRoleMenuTreeData')
    //   }
    // })
  },
  methods: {
    searchTreeData() {
      clearTimeout(this.timeOut)
      this.timeOut = setTimeout(() => {
        this.$refs.tree.filter(this.filterText);
      }, 500)
    },
    // 过滤
    filterNode(value, data) {
      if (!value) return true;
      return data.name.indexOf(value) !== -1;
    },
    // 实现单选
    handleMetaNodeClick(item, node, self) {
      if (node === true) {
        this.editCheckId = item.id;
        this.$refs["tree"].setCheckedKeys([item.id]);
      } else {
        if (this.editCheckId === item.id) {
          this.$refs["tree"].setCheckedKeys([item.id]);
        }
      }
    },
    nodeClick(item, node, self) {
      this.editCheckId = item.id;
      this.$refs["tree"].setCheckedKeys([item.id]);
    },
    // 选择
    treeCheck(item, data) {
      console.log(item, "treeCheck");
      this.treeObj = {
        id: item.id,
        label: item.name
      };
      this.form["parent_name"] = this.treeObj["label"];
      // console.log(this.form['parent_dept_name'], `this.form['parent_dept_name']`)
      // console.log(this.form['parent_dept_name'], `this.form['parent_dept_name']`)
    },
    // tree-展开
    openTree() {
      let treeList = this.data;
      this.$nextTick(() => {
        console.log(this.$refs.tree);
        // for (let i = 0; i < treeList.length; i++) {
        //   console.log(this.$refs['tree'].store.nodesMap[treeList[i].id])
        //   // this.$refs['tree'].store.nodesMap[treeList[i].id].expanded = false
        // }
      });
    },
    // tree-收缩
    foldTree() {
      let treeList = this.data;
      this.$nextTick(() => {
        console.log(this.$refs.tree);
        // console.log(this.$refs.tree.store._getAllNodes().length)
        // // for (let i = 0; i < treeList.length; i++) {
        // //   this.$refs['tree'].store.nodesMap[treeList[i].id].expanded = true
        // // }
      });
    },
    // 部门选择-确认
    selectDepartConfirm() {
      this.form["parent_id"] = this.treeObj["id"];
      // console.log(this.form['parent_dept_name'])
      this.dialogVisibleMenu = false;
    },
    // 部门选择-取消
    selectDepartCancel() {
      this.treeObj = {};
      this.dialogVisibleMenu = false;
    },
    // 菜单唯一性
    async menuNameCheck() {
      if (this.form["menu_name"] === "") {
        this.form['checkParam']["uniqueMenuName"] = false;
      } else {
        this.form['checkParam']["uniqueMenuName"] = await this.checkUnique(
          "/system/api/Menu/CheckMenuNameUnique",
          {
            menu_name: this.form["menu_name"],
            parent_id: this.form["parent_id"]
          }
        );
      }
    },
    // handleConfirm() {
    //   this.$emit("handleConfirm", this.checkParam);
    // },
    // handleCancel() {
    //   this.$emit("handleCancel");
    // }
  },
  watch: {
    titles: {
      handler(val) {
        if (val === "新增") {
          this.moduleHidden = false;
        } else {
          this.moduleHidden = true;
        }
      },
      immediate: true
    },
    // // 过滤字段
    // filterText(val) {
    //   this.$refs.tree.filter(val);
    // },
    // 部门弹窗监听
    dialogVisibleMenu: {
      handler(val) {
        if(!val) {
          this.filterText = ''
          this.editCheckId = ''
          // this.treeObj = {}
        }
      },
      immediate: true
    },
    // // 如果是子集新增存在id可查找父级
    // "form.pk_id": {
    //   handler(val) {
    //     if (val && !this.moduleHidden) {
    //       // 上级菜单-子集菜单新增
    //       getMenuForParent({ pid: val }).then(res => {
    //         if (res.code === 0) {
    //           this.form['parent_name'] = res["data"]['parent_name']
    //           this.form['parent_id'] = res["data"]['parent_id']
    //           // 查询菜单信息
    //           // this.menuParentInfo = res["data"] ? res["data"] : {};
    //           // this.menuForParentName = res['data']['parent_name'] ? res['data']['parent_name'] : '系统管理'
    //         }
    //       });
    //     }
    //   },
    //   immediate: true
    // }
  }
};
</script>
<style lang="scss" scoped>
.select-depart {
  width: 107px;
  line-height: 34px;
  background: linear-gradient(
    0deg,
    rgba(70, 127, 255, 1),
    rgba(126, 166, 253, 1)
  );
  box-shadow: 0px 5px 7px 0px rgba(213, 215, 218, 0.9);
  border-radius: 4px;
  color: rgba(255, 255, 255, 1);
  text-align: center;
  cursor: pointer;
}
</style>
